package cc.linker.steplink.crm.controller;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取中台服务接口返回值
 * 透传接口
 */
@RestController
@RequestMapping("/comm")
public class CommDataController {

    /**
     * #中台appid
     * system.middle.appId=93ESCpkn
     * #中台产品服务
     * system.middle.productUrl=http://192.1.2.166:8091
     * #中台订单服务
     * system.middle.orderUrl=http://192.1.2.166:8091
     * #中台账单服务
     * system.middle.tradeUrl=http://192.1.2.166:8091
     */


    @Value("${system.middle.appId}")
    private String appId;
    @Value("${system.middle.productUrl}")
    private String productUrl;
    @Value("${system.middle.orderUrl}")
    private String orderUrl;
    @Value("${system.middle.tradeUrl}")
    private String tradeUrl;

    private final HttpService httpService;
    private final UserInfoUtil userInfoUtil;
    private final CommonsService commonsService;
    public CommDataController(HttpService httpService, UserInfoUtil userInfoUtil, CommonsService commonsService) {
        this.httpService = httpService;
        this.userInfoUtil = userInfoUtil;
        this.commonsService = commonsService;
    }

    @PostMapping("/getMiddleData")
    public Object getMiddleData(@RequestBody Map<String, Object> param, HttpServletRequest request) throws IOException, URISyntaxException {
        PcUserInfo pcUserInfo = userInfoUtil.getPcUserInfo(request);
        param.put("orgId",pcUserInfo.getOrgId());
        Map<String, String> headMap = new HashMap<String, String>() {{
            put("Content-Type", "application/json;charset=UTF-8");
            put("appId", appId);
        }};
        String url = "";
        if(!StringUtils.isEmpty(param.get("middleServiceName"))){
            switch (param.get("middleServiceName").toString()){
                case "productMiddle" :
                    url = productUrl;
                    break;
                case "orderMiddle" :
                    url = orderUrl;
                    break;
                case "tradeMiddle" :
                    url = tradeUrl;
                    break;
                default:
                    throw GlobalException.build("该服务不存在");
            }
        }
        if("get".equals(param.get("getDataType"))){
            return httpService.doGet(url + param.get("middleApiUrl"), param, headMap);
        }
        if("post".equals(param.get("getDataType"))){
            return httpService.doPost(url + param.get("middleApiUrl"), JSON.toJSONString(param), headMap);
        }
        return null;
    }

    @GetMapping("/exportList")
    public void exportSendList(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        String queryString = request.getQueryString();
        Map<String,Object> queryParam = new HashMap<>();
        PcUserInfo pcUserInfo = userInfoUtil.getPcUserInfo(request);
        queryParam.put("orgId",pcUserInfo.getOrgId());
        Map<String, String> headMap = new HashMap<String, String>() {{
            put("Content-Type", "application/json;charset=UTF-8");
            put("appId", appId);
        }};
        if(!StringUtils.isEmpty(queryString)){
            String[] split = queryString.split("&");
            for(String str:split){
                if(!StringUtils.isEmpty(str)){
                    String[] split1 = str.split("=");
                    if(split1.length==1){
                        queryParam.put(split1[0],"");
                    }else if (split1.length==2) {
                        queryParam.put(split1[0],split1[1]);
                    }
                }
            }
        }
        String url = "";
        if(queryParam.containsKey("middleServiceName") && !StringUtils.isEmpty(queryParam.containsKey("middleServiceName"))){
            if(!StringUtils.isEmpty(queryParam.get("middleServiceName"))){
                switch (queryParam.get("middleServiceName").toString()){
                    case "productMiddle" :
                        url = productUrl;
                        break;
                    case "orderMiddle" :
                        url = orderUrl;
                        break;
                    case "tradeMiddle" :
                        url = tradeUrl;
                        break;
                    default:
                        throw GlobalException.build("该服务不存在");
                }
            }
        }
        String res = "";
        if("get".equals(queryParam.get("getDataType"))){
            res = httpService.doGet(url + queryParam.get("middleApiUrl"), queryParam, headMap);
        }
        if("post".equals(queryParam.get("getDataType"))){
            res = httpService.doPost(url + queryParam.get("middleApiUrl"), JSON.toJSONString(queryParam), headMap);
        }
        Map map = JSON.parseObject(res, Map.class);
        if(200 == (int)map.get("code")){
            Map<String,Object> data = (Map<String,Object>)map.get("data");
            JSONArray keys = JSON.parseArray(data.get("key").toString());
            String[] key = keys.toArray(new String[]{});
            JSONArray titles = JSON.parseArray(data.get("title").toString());
            String[] title = titles.toArray(new String[]{});
            String fileName = data.get("fileName").toString();

            JSONArray datas = JSON.parseArray(data.get("data").toString());
            List<Map<String,Object>> resData = new ArrayList<>();
            datas.stream().forEach(pb -> {
                Map<String, Object> rightMap = (Map<String, Object>) pb;
                resData.add(rightMap);
            });
            commonsService.excelDownload(resData,key,title,fileName,response);
        }
    }
}
